<?php
namespace App\Admin\Controllers\Products;

use App\Admin\Actions\Products\Classify\DisableItem;
use App\Admin\Actions\Products\Classify\EnableItem;
use App\Exporter\Products\ProductClassifyExporter;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;
use Encore\Admin\Widgets\Box;
use Illuminate\Support\Facades\DB;

class ClassifyController extends AdminController{

    protected $title = '品类管理';

    public function index(Content $content)
    {
        return $content
            ->title($this->title())
            ->description(trans('admin.list'))
            ->row(function (Row $row) {
                $row->column(6, $this->grid());
                if(Admin::user()->can('classify.edit')){
                    $row->column(6, function (Column $column) {
                        $form = new \Encore\Admin\Widgets\Form();
                        $form->action(admin_url('products/classify'));

                        $form->select('season', '季节性')->options(ProductClassify::$_season)->rules('required')->required();
                        $form->text('title', '品类')
                            ->creationRules(['required', "unique:product_classify"],['required' => '品类必填','unique' => '品类已存在'])
                            ->updateRules(['required', "unique:product_classify,model_no,{{id}}"],['required' => '品类必填','unique' => '品类已存在']);
                        $form->text('model_no', 'ModelNo')->creationRules(["unique:product_classify"],['unique' => 'ModelNo已存在'])
                            ->updateRules(["unique:product_classify,title,{{id}}"],['unique' => 'ModelNo已存在']);
                        $form->display('ModelNo说明')->default("1. 亚马逊产品：MDN+该品类第一个SKU的尾数<br/>
   &nbsp;&nbsp;&nbsp;&nbsp;举例：加厚加宽充气睡垫 - Model NO为MDN05092<br/>
2. 品牌产品：品牌SKU编码规则前四个字段：品类名+款号+年份+季节<br/>
   &nbsp;&nbsp;&nbsp;&nbsp;举例：人体曲线睡垫 ErgoRest-R3.8 - Model NO为SLP0623SS");

                        $form->hidden('_token')->default(csrf_token());

                        $column->append((new Box(trans('admin.new'), $form))->style('success'));
                    });
                }
            });
    }

    protected function grid()
    {
        $grid = new Grid(new ProductClassify());
        $grid->model()->where('id', '>', 0)
            ->orderBy('id', 'DESC');
        $grid->column('id','ID');
        $grid->column('season','季节性')->display(function ($v){
            return ProductClassify::$_season[$v];
        })->filter(ProductClassify::$_season);
        $grid->column('title','品类');
        $grid->column('model_no','ModelNo');
        $grid->column('status','启用')->bool([1 => true, 2 => false])->filter(ProductClassify::$_status);
        $grid->column('report_status','开放')->bool([1 => true, 2 => false])->filter(ProductClassify::$_reportStatus)->help('销量报表品类查阅权限');

        if(Admin::user()->can('classify.edit')){
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableDelete();
            });
            $grid->batchActions(function (Grid\Tools\BatchActions $batch) {
                $batch->disableDelete();
                $batch->add(new DisableItem());
                $batch->add(new EnableItem());
            });
        }else{
            $grid->disableActions();
            $grid->disableBatchActions();
        }
        $grid->disableCreateButton();
        $grid->exporter(new ProductClassifyExporter());
        $grid->quickSearch('title');
        $grid->disableFilter();

        return $grid;
    }

    public function edit($id,Content $content)
    {
        return $content
            ->title($this->title())
            ->description('编辑')
            ->row($this->form()->edit($id));
    }

    protected function form()
    {
        $form = new Form(new ProductClassify());

        $form->select('season', '季节性')->options(ProductClassify::$_season)->rules('required')->required()->setWidth(3);
        $form->text('title', '品类')
            ->creationRules(['required', "unique:product_classify"],['required' => '品类必填','unique' => '品类已存在'])
            ->updateRules(['required', "unique:product_classify,title,{{id}}"],['required' => '品类必填','unique' => '品类已存在'])->setWidth(3);
        $form->text('model_no', 'ModelNo')
            ->creationRules(["unique:product_classify"],['unique' => 'ModelNo已存在'])
            ->updateRules(["unique:product_classify,model_no,{{id}}"],['unique' => 'ModelNo已存在'])->setWidth(3);
        $form->display('ModelNo说明')->default("1. 亚马逊产品：MDN+该品类第一个SKU的尾数<br/>
   &nbsp;&nbsp;&nbsp;&nbsp;举例：加厚加宽充气睡垫 - Model NO为MDN05092<br/>
2. 品牌产品：品牌SKU编码规则前四个字段：品类名+款号+年份+季节<br/>
   &nbsp;&nbsp;&nbsp;&nbsp;举例：人体曲线睡垫 ErgoRest-R3.8 - Model NO为SLP0623SS");
        $form->switch('status', '启用')->states(statusSwitch())->default('1');
        $form->switch('report_status', '开放')->states(statusSwitch())->default('1')->help('月利润报表品类查阅权限，默认开放');

        $form->saving(function (Form $form) {

            if($form->isEditing()){

                /******(品类状态启用/停用) start********/
                if ($form->status == 'on') {
                    //启用
                    $skuList = ProductSku::getProductSkuList($form->model()->id, ProductSku::STATUS_NO);
                    if ($skuList) {
                        foreach ($skuList as $key => $val){
                            //更新亚马逊sku (启用)
                            $amazonSkuList = ProductAmazonSku::getProductAmazonSkuList($val->id, ProductAmazonSku::STATUS_NO);
                            if ($amazonSkuList) {
                                foreach ($amazonSkuList as $k => $v){
                                    $v->status = ProductAmazonSku::STATUS_YES;
                                    $v->save();
                                }
                            }

                            //更新公司sku (启用)
                            $val->status = ProductSku::STATUS_YES;
                            $val->save();
                        }
                    }
                }else{
                    //停用
                    //验证品类下产品的个数(正常产品sku)
                    $skuCount = ProductSku::getClassifyProductSkuCount(null, $form->model()->id, ProductSku::STATUS_YES);
                    if ($skuCount > 0) {
                        admin_error('ERROR', '该品类下存在正常sku, 请停用淘汰相关sku后, 重新尝试');
                        return back()->withInput();
                    }else{
                        //停用品类下的淘汰产品
                        $skuList = ProductSku::getProductSkuList($form->model()->id, null, ProductSku::PSKUSTATUS_OUT);
                        foreach ($skuList as $key => $val){
                            //更新亚马逊sku(停用)
                            $amazonSkuList = ProductAmazonSku::getProductAmazonSkuList($val->id, ProductAmazonSku::STATUS_YES);
                            if ($amazonSkuList){
                                foreach ($amazonSkuList as $k => $v){
                                    $v->status = ProductAmazonSku::STATUS_NO;
                                    $v->save();
                                }
                            }

                            //更新公司sku(停用)
                            $val->status = ProductSku::STATUS_NO;
                            $val->save();
                        }
                    }
                }
                /*******end*******/

            }
        });

        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
            $tools->disableDelete();
        });

        return $form;
    }



}
